/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Common.Utilities;
using DNNContentBuilder.UserControls.FieldControls;

namespace DNNContentBuilder.UserControls
{
	using System;

	/// <summary>
	///		Summary description for FormEngine.
	/// </summary>
	public class FormEngine : System.Web.UI.UserControl
	{
		#region Controls
		protected System.Web.UI.WebControls.PlaceHolder plcFields;
		#endregion

		#region Member Variables
		private Hashtable formlets = new Hashtable();
		private ControlTypeController ctController = new ControlTypeController();
		#endregion

		#region Properties
		/// <summary>
		/// Gets the name of the table associated with this 
		/// FormEngine instance.
		/// </summary>
		[Bindable(true)]
		[Browsable(false)]
		[DefaultValue("")]
		public string TableName
		{
			get
			{
				object viewState = this.ViewState["TableName"];

				if (viewState == null)
				{
					viewState = Request.Params["cbFETable"];

					// If not specified, invalidate the property
					if (viewState == null)
					{
						viewState = String.Empty;
					}
				}

				return (string)viewState;
			}
			set
			{
				this.ViewState["TableName"] = value;
			}
		}

		/// <summary>
		/// Gets or sets the ID of the form definition being handled 
		/// by this instance of the Form Engine.
		/// </summary>
		[DefaultValue(-1)]
		public int FormDefinitionId
		{
			get
			{
				object viewState = this.ViewState["FormDefinitionId"];

				if (viewState != null)
				{
					return (int)viewState;
				}

				return Null.NullInteger;
			}
			set
			{
				this.ViewState["FormDefinitionId"] = value;
			}
		}

		public Hashtable Formlets
		{
			get
			{
				return formlets;
			}
		}
		#endregion

		#region Event Handlers
		/// <summary>
		/// Handles the <see cref="System.Web.UI.Control.Load"/> event.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Could have been called elsewhere, e.g., Render()
			if (this.formlets.Count == 0)
			{
				this.LoadFields();
			}
		}
		#endregion

		#region Implementation
		/// <summary>
		/// Load and render the fields contained in the form specification
		/// for the associated module.
		/// </summary>
		private void LoadFields()
		{
			ArrayList fields = DbContentController.GetFields(this.FormDefinitionId);

			// Refuse to render any controls if no primary key field is defined
			if (!IsPrimaryKeyDefined(fields))
			{
				return;
			}

			// Check if a child table has been specified
			if (this.TableName == null)
			{
				this.TableName = FormEngine.GetDrivingTable(fields);
			}

			// Check if a table could obtained
			if (this.TableName.Length == 0)
			{
				return;
			}

			if (fields.Count > 0)
			{
				FormDefinitionController fdController = new FormDefinitionController();
				FormDefinitionInfo fdInfo = fdController.GetItem(this.FormDefinitionId);
				
				string style = String.Format("<style>{0}</style>", fdInfo.CSS);
				
				plcFields.Controls.Add(new LiteralControl(style));	
			}

			foreach (FieldDefinitionInfo fdInfo in fields)
			{
				if (this.CanRender(fdInfo))
				{
					this.RenderControl(fdInfo);
				}
			}
		}

		/// <summary>
		/// Determines if a <see cref="FieldDefinitionInfo"/> can or cannot
		/// be rendered in the current context.
		/// </summary>
		/// <param name="fdInfo"></param>
		/// <returns></returns>
		private bool CanRender(FieldDefinitionInfo fdInfo)
		{
			string tableName = fdInfo.SourceField;

			if (fdInfo.XML.IndexOf("<Linker") == 0)
			{
				XmlDocument xd = new XmlDocument();
				xd.LoadXml(fdInfo.XML);

				XmlNode node = xd.SelectSingleNode("//LinkedField");

				tableName = node.InnerText;
			}

			return fdInfo.Visible && !fdInfo.IsPrimaryKey && tableName.IndexOf(this.TableName + ".") != -1;
		}

		/// <summary>
		/// Renders a user control that implements the <see cref="IFormlet"/>
		/// interface in a user specified manner.
		/// </summary>
		/// <param name="fdInfo"></param>
		private void RenderControl(FieldDefinitionInfo fdInfo)
		{
			ControlTypeInfo ctInfo = ctController.GetItem(fdInfo.ControlTypeId);
					
			string controlPath  = Page.ResolveUrl("~/" + ctInfo.ControlPath).Replace("Def.", "Control.");
			UserControl formlet = (UserControl)Page.LoadControl(controlPath);

			if (fdInfo.Tooltip != null && fdInfo.Tooltip.Length > 0)
			{
				foreach (Control c in formlet.Controls)
				{
					// TODO: handle composite controls (i.e., check for c.HasControls())
					if (c is WebControl)  ((WebControl)c).ToolTip = fdInfo.Tooltip;
					if (c is HtmlControl) ((HtmlControl)c).Attributes["title"] = fdInfo.Tooltip;
				}
			}

			// Assert that we're dealing with a control that implements IFormlet
			ArgumentValidator.AssertExpectedType(formlet, typeof(IFormlet), "ERR_INVALID_FORMLET");

			if (formlet is LinkerControl)
			{
				// TODO: remove LinkerControl coupling
				((LinkerControl)formlet).FieldDefinition = fdInfo;
			}

			plcFields.Controls.Add(new LiteralControl("<tr><td width='130'>"));
			plcFields.Controls.Add(new LiteralControl(fdInfo.Title));
			plcFields.Controls.Add(new LiteralControl("</td>"));

			plcFields.Controls.Add(new LiteralControl("<td>"));
			plcFields.Controls.Add(formlet);
			plcFields.Controls.Add(new LiteralControl("</td></tr>"));

			//Inserting CSS info into control specific XML
			string xml = Commons.InsertChildNode("<CssClass>" + fdInfo.CssClass + "</CssClass>", fdInfo.XML);
			
			((IFormlet)formlet).SetConfig(xml);

			this.formlets.Add(fdInfo.SourceField, formlet);
		}

		public void Render(ArrayList fields, DataRow row)
		{
			// Could have been called elsewhere
			if (this.formlets.Count == 0)
			{
				LoadFields();
			}

			foreach (FieldDefinitionInfo fdInfo in fields)
			{
				if (CanRender(fdInfo))
				{
					DisplayControlContents(fdInfo, row);
				}
			}
		}

		/// <summary>
		/// Display the contents of a specified field.
		/// </summary>
		/// <param name="fdInfo"></param>
		private void DisplayControlContents(FieldDefinitionInfo fdInfo, DataRow dr)
		{
			string fieldName = fdInfo.SourceField.Split('.')[1];

			IFormlet formlet = (IFormlet)this.formlets[fdInfo.SourceField];
		
			string xml = formlet.GetValue(ContextUtil.GetTypeXml());

			XmlDocument xd = new XmlDocument();
			
			xd.LoadXml(xml);
			
			try {
				xd.SelectSingleNode("//Value").InnerXml = Commons.EncodeAngleBrackets(dr[fdInfo.SourceField].ToString());
			}
			catch (Exception ) {
				xd.SelectSingleNode("//Value").InnerXml = System.Web.HttpUtility.HtmlEncode(dr[fdInfo.SourceField].ToString());
			}
			
			formlet.SetValue(xd.InnerXml);
		}

		/// <summary>
		/// Determines whether a primary key field is defined in a list of 
		/// <see cref="FieldDefinitionInfo"/> objects.
		/// </summary>
		/// <param name="fields"></param>
		/// <returns></returns>
		private bool IsPrimaryKeyDefined(ArrayList fields)
		{
			return FormEngine.GetPrimaryKeyField(fields) != null;
		}

		/// <summary>
		/// Gets the name of the table for the first primary key field
		/// defined in the fields array.
		/// </summary>
		/// <param name="fields"></param>
		/// <returns></returns>
		public static string GetDrivingTable(ICollection fields)
		{
			FieldDefinitionInfo pkInfo = GetPrimaryKeyField(fields);

			if (pkInfo != null)
			{
				return pkInfo.SourceField.Split('.')[0];
			}

			return null;
		}

		/// <summary>
		/// Gets the first primary key field 
		/// </summary>
		/// <param name="fields"></param>
		/// <returns></returns>
		public static FieldDefinitionInfo GetPrimaryKeyField(ICollection fields)
		{
			foreach (FieldDefinitionInfo fdInfo in fields)
			{
				if (fdInfo.IsPrimaryKey)
				{
					return fdInfo;
				}
			}

			return null;
		}
		#endregion

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
		}
		#endregion
	}
}
